package com.sun.hunk.struts.action;

import com.sun.hunk.hibernate.DAOFactory;
import com.sun.hunk.hibernate.domain.Role;
import com.sun.hunk.hibernate.domain.User;
import com.sun.hunk.struts.HunkDispatchAction;
import com.sun.hunk.struts.form.UserForm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 *
 * @author sunil
 */
public class UserAction extends HunkDispatchAction {

    public ActionForward signup(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        UserForm userForm = (UserForm) form;
        User user = userForm.getUser();
        String error = validateUserRegistration(user);
        if (error != null) {
            setError(request, error);
            return mapping.findForward("signup");
        } else {
            Role role = DAOFactory.getRoleDAO().getDefaultRole();
            user.addRole(role);
            DAOFactory.getUserDAO().saveOrUpdate(user);
            setMessage(request, "Your account has been created successfully ! You are ready to login.");
            return mapping.findForward("login");
        }
    }

    public String validateUserRegistration(User user) {
        if (!DAOFactory.getUserDAO().isLoginNameAvailable(user.getLoginName())) {
            return "Soory ! Login name you requested for is not available";
        } else {
            return null;
        }
    }

    public ActionForward search(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        UserForm userForm = (UserForm) form;
        request.setAttribute("userList", DAOFactory.getUserDAO().findUsers(userForm.getUser()));
        return mapping.findForward("users");
    }

    public ActionForward delete(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        UserForm userForm = (UserForm) form;
       // DAOFactory.getUserDAO().delete(userForm.getUser());
        search(mapping, form, request, response);
        return mapping.findForward("userList");
    }
}
